import React, { Component } from 'react';
import { connect } from 'dva';
import style from "styled-components";
import {
  Form, Input, Select, Button, Radio,DatePicker,Cascader,Modal,message
} from 'antd';
import Drawer from 'react-motion-drawer';
import * as ajax from "../../../services/api";
import './less/report.less';



const FormItem = Form.Item;
const { Option } = Select;
const {TextArea} = Input;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;

@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class AddManagementlist extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open:this.props.visible,
      loading:false,
      // comId:1,
      comManagerId: this.props.comManagerId,//传过来的方案id
      nationList:[],
      idCardType:'',
      idCardList:[],
      educationList:[],
      skillList:[],
      areas: [],//地区
      listPage:{
        idCardType:'',
        idCardNo:'',
        name:'',
        sex:'',
        nation:'',
        residentProvince:'',
        residentCity:'',
        residentArea:'',
        residenceAddress:'',
        telephone:'',
        education:'',
        positionName:'',
        domicileProvince:'',
        domicileCity:'',
        domicileArea:'',
        domicileAddress:'',
        jobSkillLevel:'',
      },
      fan:false,
    }
  }
  //重置表单
resetFrom = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({
        idCardNo:'',
        name:'',
        sex:'',
        nation:'',
        residentProvince:'',
        residentCity:'',
        residentArea:'',
        residenceAddress:'',
        telephone:'',
        education:'',
        positionName:'',
        domicileProvince:'',
        domicileCity:'',
        domicileArea:'',
        domicileAddress:'',
        jobSkillLevel:'',
    });

  }
  componentWillReceiveProps(props) {
    this.setState({ open: props.visible,comManagerId:props.comManagerId },() => {
      console.log(this.state.open,this.state.comManagerId)
    });
    this.addManagementList();
    this.nationListCon();//民族
    this.getDistrict();
    this.getIdCard();
    this.getEducation();
    this.getSkill();
  }

  componentDidMount() {
    this.props.onRef(this);
    // this.addManagementList();
    // this.nationListCon();//民族
    // this.getDistrict();
    // this.getIdCard();
    // this.getEducation();
    // this.getSkill();
  }

  addManagementList = () => {
     if(this.state.comManagerId !== '00'){
       console.log(this.state.comManagerId);
       ajax.comStockGetManageById({comManagerId:this.state.comManagerId}).then((data)=>{
         if(data.data){
           this.setState({
             listPage:data.data,
           })
         }
       })
     }
  };

  nationListCon = () => {
    ajax.getDictInformation({codeTypes:'nation'}).then((data)=>{
      if (data.data) {
        this.setState({
          nationList: data.data.nation,
        });
      }
    })
  };

  //省市区
  getDistrict = () => {
    ajax.getDistrictData().then((data) => {
      console.log('省市区data:', data);
      let areas = data.data.map((val) => {
          return {
            value: val.regionId,
            label: val.regionName,
            children:val.childs.map((valChild) => {
              return {
                value: valChild.regionId,
                label: valChild.regionName,
                children:valChild.childs.map((valChildChild) => {
                  return {
                    value: valChildChild.regionId,
                    label: valChildChild.regionName,
                  }
                })
              }
            })
          };
        }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas: areas,
      });
    })
  };

  getIdCard = () => {
    ajax.getDictInformation({codeTypes:'idCardType_bak'}).then((data)=>{
      if (data.data) {
        this.setState({
          idCardList: data.data.idCardType_bak,
        });
      }
    })
  };

  getEducation = () => {
    ajax.getDictInformation({codeTypes:'education'}).then((data)=>{
      if (data.data) {
        this.setState({
          educationList: data.data.education,
        });
      }
    })
  };

  getSkill = () => {
    ajax.getDictInformation({codeTypes:'skillLevel'}).then((data)=>{
      if (data.data) {
        this.setState({
          skillList: data.data.skillLevel,
        });
      }
    })
  };

  submitHandlerDeep = (that,values) => {
    that.setState({ loading: true });
    ajax.submitComStockSaveComManage({...values}).then((data) => {
      // message.success('管理人员信息保存成功！');
      that.setState({ loading:false });
      that.setState({
        fan:true,
      });
      that.props.close();
    },(err) => {
      console.log(err);
      that.setState({ loading:false });
    });
    // that.props.close();
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('values', values);
        values.residentProvince = values.hu[0];
        values.residentCity = values.hu[1];
        values.residentArea = values.hu[2];
        values.domicileProvince = values.ed[0];
        values.domicileCity = values.ed[1];
        values.domicileArea = values.ed[2];
        delete values.hu;
        delete values.ed;
        // values.comId = this.state.comId;
        if(this.state.comManagerId !== '00'){
          values.comManagerId = this.state.comManagerId;
        }

        let idCardTypeName = '';
        this.state.idCardList.map((val) => {
          if(val.codeValue === values.idCardType){
            idCardTypeName = val.label;
          }
          return 1;
        });
        const that = this;
        if(this.state.comManagerId !== '00'){
          that.submitHandlerDeep(that,values);
        }else{
          //确认提示
          confirm({
            title: '[' + idCardTypeName + ']：[' + values.idCardNo + ']，提交后证件类型及证件号不可修改。是否确认提交。',
            okText: '确认',
            cancelText: '取消',
            onOk() {
              that.submitHandlerDeep(that,values);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }
      }
    });
  };


  renderNationList = () => {
    return this.state.nationList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  idCardList = ()=> {
    return this.state.idCardList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  renderEducation = () => {
    return this.state.educationList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  skillList = () => {
    return this.state.skillList.map((val, key) => {
      return <Option key={key} value={val.codeValue+""}>{val.label}</Option>;
    });
  };

  fan = () => {
    let _that = this;
    if(_that.state.fan){
      // _that.props.history.push(`/enterprise/reported`);
      _that.props.close();
    }else{
      confirm({
        title: '当前信息未保存，是否确认返回？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          // _that.props.history.push(`/enterprise/reported`);
          _that.props.close();
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的联系方式！');
    } else {
      callback();
    }
  };


  //证件类型-身份证号码验证
  checkIdCardNo = (rule, value, callback) => {
    // const form = this.props.form;
    // const idType = form.getFieldValue('idCardType');
    // console.log('证件类型select发生变化的值:' + idType);
    if (value && !(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(value)) {
      callback('请输入正确的身份证号码！');
    }else{
      callback();
    }

  };
  //证件类型-普通号码验证
  checkId = (rule, value, callback) => {
    if(value && !(/^[a-zA-Z0-9]{1,20}$/).test(value)){
      callback('请输入正确的证件号码！');
    }else{
      callback();
    }
  };

  //身份证改变事件
  idCardTypeOnChangeHandler = (value) =>{
      // this.props.form.validateFields(['cerNo']);
      this.props.form.setFieldsValue({'idCardNo':''});
      this.setState({idCardType:value});
  };


  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const config = {
      rules: [{ type: 'object', required: true, message: '请选择日期!' }],
    };

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };


    return (
      <Drawer
        overlayColor="rgba(0, 0, 0,0)"
        right
        open={this.state.open}
        noTouchClose
        width={600}
        zIndex={2}
        className="drawer-box"
        onChange={(open) => {
          this.props.onChange(open);
          this.setState({ open });
        }}
      >
      <Container>
      <div className="ManagementAdd">
       <header className="body-header" style={{"paddingLeft":'20px',"paddingTop":'14px'}}>管理员信息</header>
      <Form
        onSubmit={this.handleSubmit}
        style={{ marginTop: 24 }}
      ><FormItem
        {...formItemLayout}
        label="姓名"
      >
        {getFieldDecorator('name', {
          initialValue: this.state.listPage.name,
          rules: [{
            required: true, message: '请输入姓名',
          },{
            pattern:/^[a-zA-Z\u4e00-\u9fa5]+$/,
            message:'请输入8位中文或英文的姓名',
          }],
        })(
          <Input placeholder="请输入" maxLength="8"/>
        )}
      </FormItem>
        <FormItem
          {...formItemLayout}
          label="职务"
        >
          {getFieldDecorator('positionName', {
            initialValue: this.state.listPage.positionName,
            rules: [{
              required: true, message: '请输入职务',
            }],
          })(
            <Input placeholder="请输入" maxLength="10"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="性别"
        >
          {getFieldDecorator('sex',{
            initialValue: this.state.listPage.sex,
          })(
            <RadioGroup>
              <Radio value="1">男</Radio>
              <Radio value="2">女</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="民族"
        >
          {getFieldDecorator('nation',
            {
              initialValue: this.state.listPage.nation,
            rules: [{ required: false, message: '请选择民族' }],
          })(
            <Select placeholder="请选择">
              {/* <Option value="">请选择</Option> */}
              {this.renderNationList()}
            </Select>
          )}
        </FormItem>
        {this.state.comManagerId === '00' ? <FormItem
          {...formItemLayout}
          label="户籍"
        >
          {getFieldDecorator('hu', {
            rules: [{ required: true, message: '请选择户籍' }],
          })(
            <Cascader options={this.state.areas} placeholder="请选择" />
          )}
        </FormItem> :<FormItem
          {...formItemLayout}
          label="户籍"
        >
          {getFieldDecorator('hu', {
            initialValue:[this.state.listPage.residentProvince,this.state.listPage.residentCity,this.state.listPage.residentArea],
            rules: [{ required: true, message: '请选择户籍' }],
          })(
            <Cascader options={this.state.areas} placeholder="请选择" />
          )}
        </FormItem>}
        <FormItem
          {...formItemLayout}
          label="证件类型"
        >
          {getFieldDecorator('idCardType', {
            initialValue:this.state.listPage.idCardType,
            rules: [{ required: true, message: '请选择证件类型' }],
          })(
            <Select disabled={this.state.comManagerId !== '00'} placeholder="请选择" onChange={this.idCardTypeOnChangeHandler} >
              {this.idCardList()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="证件号"
        >
          { this.state.idCardType === '1'?
            getFieldDecorator('idCardNo', {
              initialValue:this.state.listPage.idCardNo,
              rules: [{
                required: true, message: '请输入证件号',
              },{
                validator: this.checkIdCardNo
              }],
            })(
              <Input disabled={this.state.comManagerId !== '00'} placeholder="请输入" maxLength="20"/>
            )
            :
            getFieldDecorator('idCardNo', {
              initialValue:this.state.listPage.idCardNo,
              rules: [{
                required: true, message: '请输入证件号',
              },{
                validator: this.checkId
              }],
            })(
              <Input disabled={this.state.comManagerId !== '00'} placeholder="请输入" maxLength="20"/>
            )
          }
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="联系方式"
        >
          {getFieldDecorator('telephone', {
            initialValue:this.state.listPage.telephone,
            rules: [{
              required: true, message: '请输入联系方式',
            }, {
              validator: this.checkPhone
            }],
          })(
            <Input placeholder="请输入" maxLength="11"/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="学历"
        >
          {getFieldDecorator('education', {
            initialValue:this.state.listPage.education,
            rules: [{ required: true, message: '请选择学历' }],
          })(
            <Select placeholder="请选择">
              {/* <Option value="0">请选择</Option> */}
              {this.renderEducation()}
            </Select>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="职业技能等级"
        >
          {getFieldDecorator('jobSkillLevel',{
            initialValue:this.state.listPage.jobSkillLevel,
          })(
            <Select placeholder="请选择">
              {/* <Option value="0">请选择</Option> */}
              {this.skillList()}
            </Select>
          )}
        </FormItem>
        {this.state.comManagerId === '00' ?  <FormItem
          {...formItemLayout}
          label="居住地址"
        >
          {getFieldDecorator('ed', {
            rules: [{ required: true, message: '请选择居住地址' }],
          })(
            <Cascader options={this.state.areas} placeholder="请选择" />
          )}
        </FormItem> :  <FormItem
          {...formItemLayout}
          label="居住地址"
        >
          {getFieldDecorator('ed', {
            initialValue:[this.state.listPage.domicileProvince,this.state.listPage.domicileCity,this.state.listPage.domicileArea],
            rules: [{ required: true, message: '请选择居住地址' }],
          })(
            <Cascader options={this.state.areas} placeholder="请选择" />
          )}
        </FormItem>}
        <FormItem
          {...formItemLayout}
          label=" "
          colon={false}
          className="detailedAddress"
        >
          {getFieldDecorator('domicileAddress', {
            initialValue:this.state.listPage.domicileAddress,
            rules: [{
              required: true,message:'居住具体地址不能为空'
            }],
          })(
            <TextArea row={2} placeholder="请输入" maxLength="50"/>
          )}
        </FormItem>
        <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
          <Button loading={submitting} onClick={this.fan}>
            返回
          </Button>
          <Button type="primary" style={{ marginLeft: 8 }} loading={this.state.loading} htmlType="submit">提交</Button>
        </FormItem>
      </Form>
      </div>
      </Container>
      </Drawer>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
  color: #333;
  .body-header{
      font-size: 20px;
      color: #333333;
      padding-bottom:16px;
      border-bottom:1px solid #e9e9e9;
  }
}`;
